// WWL.include ( 'popbox' );

WWL.menu = function ( name )
{
	var menu = new WWL ( 'menu', name );

	menu.tbar = new WWL.toolbar ( 'tbar_' + name );
	menu._event_names = [];	// Toolbar has no "direct" events
	menu.tbar.mode = "H";


	menu.create = function ( menu_def, block_auto_close )
	{
		var t, l = menu_def.length;
		var itm;

		menu._menu_def = menu_def;

		menu.tbar.clear ();

		for ( t = 0; t < l; t ++ )
			menu._add_sub_item ( menu.tbar, menu_def [ t ], t, menu._menu_def, 0 );

		menu._sub_menus = [];

		if ( ! block_auto_close )
			liwe.events.add ( document, 'click', function () 
				{ 
					if ( menu._block_close )
						menu._block_close = false;
					else
						menu._clear_subs (); 
				} );
	};


	menu._add_sub_item = function ( obj, itm, t, menu_def, depth )
	{
		var old_cback = itm [ 'cback' ];

		if ( itm [ 'menu' ] )
		{
			itm [ 'cback' ] =  function ( widget, event_name, div, evt ) 
				{ 
					menu._block_close = true; 
					menu._clear_subs ( depth ); 
					menu._show_submenu ( div, t, menu_def [ t ] [ 'menu' ], depth );
				};

			itm [ 'block_auto_close' ] = true;

			obj.add_item ( itm );

			return;
		}

		itm [ 'cback' ] = function ( widget, event_name, div, evt ) 
			{ 
				menu._block_close = true;
				menu._clear_subs (); 
				if ( old_cback ) return old_cback ( widget, event_name, div, evt ); 
				return null;
			};

		if ( itm.get ( "txt" ) ) itm [ 'txt' ] = itm [ 'txt' ].replace ( / /g, "&nbsp;" );
		obj.add_item ( itm );
	};

	menu._clear_subs = function ( depth )
	{
		var t, l = menu._sub_menus.length;

		if ( ! depth )
		{
			for ( t = 0; t < l; t ++ ) menu._sub_menus [ t ].box.destroy ();
			menu._sub_menus = [];
			return;
		} 

		//console.debug ( "Len: " + l + " - Depth: " + depth );

		l -= depth;
		if ( l <= 0 ) return;

		for ( t = 0; t < l; t ++ )
		{
			var p = menu._sub_menus.pop ();
			p.box.destroy ();
		}
	};

	menu._show_submenu = function ( div, pos, menu_def, depth )
	{
		var popm = new WWL.popmenu ( 'popmenu_' + 'pop:' + pos + ":" + depth );
		var t, l = menu_def.length;

		for ( t = 0; t < l; t ++ )
			menu._add_sub_item ( popm, menu_def [ t ], t, menu_def, depth + 1 );

		if ( depth > 0 ) {
			popm.set_parent ( div, 'R' );
			popm.box.set_size ( 0, 0 );
		} else {
			popm.set_parent ( div );
			popm.box.set_size ( div.offsetWidth, 0 );
		}

		popm.show ();

		menu._sub_menus.push ( popm );
	};

	menu.to_string = function () { return '<div id="' + this.id + '">' + menu.tbar.to_string () + '</div>'; };

	// menu.get_item

	return menu;
};

WWL.menu.get_instance = function ( instance_name )
{
	return WWL.get_instance ( "menu", instance_name );
};

